package adkr

import (
	"encoding/json"
	"log"
	"math/big"
	"strconv"
	"sync"
	"time"
	
	// 导入DyCAPS模块
	"ebbflow/cbr_protocol/dycaps"
)

// CBRConfig CBR协议配置
type CBRConfig struct {
	// 门限参数 - 使用t+l+1
	T int `json:"t"`
	L int `json:"l"`
	N int `json:"n"`
	
	// KZG参数
	KzgPP []byte `json:"kzg_pp"`
	
	// 超时设置
	Timeout time.Duration `json:"timeout"`
}

// CBRProtocol CBR协议结构
type CBRProtocol struct {
	config     *CBRConfig
	dycaps     *dycaps.DyCAPS
	mu         sync.RWMutex
	state      ProtocolState
	checkpoint *Checkpoint
}

// ProtocolState 协议状态
type ProtocolState int

const (
	StateIdle ProtocolState = iota
	StateRunning
	StateReconfiguring
	StateComplete
)

// Checkpoint 检查点结构
type Checkpoint struct {
	Epoch       int                    `json:"epoch"`
	Committee   dycaps.Committee        `json:"committee"`
	TPK         []byte                  `json:"tpk"`
	PKVec       []byte                  `json:"pk_vec"`
	ShareMap    map[string][]byte       `json:"share_map"`
	Commitments []byte                  `json:"commitments"`
	Digest      []byte                  `json:"digest"`
	Signature   []byte                  `json:"signature"`
}

// NewCBRProtocol 创建新的CBR协议实例
func NewCBRProtocol(config *CBRConfig, rbc dycaps.RBCInterface, mvba dycaps.MVBAInterface, threshold dycaps.ThresholdSigInterface) *CBRProtocol {
	// 创建DyCAPS实例
	dycapsInstance := dycaps.NewDyCAPS(rbc, mvba, threshold)
	
	return &CBRProtocol{
		config: config,
		dycaps: dycapsInstance,
		state:  StateIdle,
	}
}

// ReconfigureWithCBR 使用CBR协议进行重配置
func (c *CBRProtocol) ReconfigureWithCBR(oldCommittee, newCommittee dycaps.Committee) error {
	log.Printf("[CBR] Starting reconfiguration with CBR protocol")
	
	c.mu.Lock()
	c.state = StateReconfiguring
	c.mu.Unlock()
	
	// 验证委员会参数
	if err := c.validateCommittees(oldCommittee, newCommittee); err != nil {
		return err
	}
	
	// 执行DyCAPS handoff协议
	params := dycaps.HandoffParams{
		KzgPP:     c.config.KzgPP,
		OldCommit: c.checkpoint.Commitments,
	}
	
	result, err := c.dycaps.Handoff(oldCommittee, newCommittee, params)
	if err != nil {
		return err
	}
	
	// 生成检查点
	checkpoint, err := c.generateCheckpoint(newCommittee, result)
	if err != nil {
		return err
	}
	
	// 安装检查点
	if err := c.installCheckpoint(checkpoint); err != nil {
		return err
	}
	
	c.mu.Lock()
	c.state = StateComplete
	c.mu.Unlock()
	
	log.Printf("[CBR] Reconfiguration completed successfully")
	return nil
}

// validateCommittees 验证委员会参数
func (c *CBRProtocol) validateCommittees(oldCommittee, newCommittee dycaps.Committee) error {
	// 检查新委员会满足n >= 3t + 2l + 1
	if newCommittee.N < 3*newCommittee.T + 2*newCommittee.L + 1 {
		return fmt.Errorf("new committee does not satisfy n >= 3t + 2l + 1")
	}
	
	// 检查门限设置
	if newCommittee.T + newCommittee.L + 1 > newCommittee.N {
		return fmt.Errorf("threshold t+l+1=%d exceeds committee size %d", 
			newCommittee.T + newCommittee.L + 1, newCommittee.N)
	}
	
	return nil
}

// generateCheckpoint 生成检查点
func (c *CBRProtocol) generateCheckpoint(newCommittee dycaps.Committee, result *dycaps.HandoffOutput) (*Checkpoint, error) {
	// 生成摘要
	digest := c.generateDigest(newCommittee, result.Commitments)
	
	// 生成阈值签名
	signature, err := c.generateThresholdSignature(digest)
	if err != nil {
		return nil, err
	}
	
	checkpoint := &Checkpoint{
		Epoch:       c.checkpoint.Epoch + 1,
		Committee:   newCommittee,
		TPK:         result.TPK,
		PKVec:       result.PKVec,
		ShareMap:    result.ShareMap,
		Commitments: result.Commitments,
		Digest:      digest,
		Signature:   signature,
	}
	
	return checkpoint, nil
}

// generateDigest 生成摘要
func (c *CBRProtocol) generateDigest(newCommittee dycaps.Committee, commitments []byte) []byte {
	// 使用相同的序列化函数
	data := make([]byte, 0)
	
	// 序列化委员会
	committeeData, _ := json.Marshal(newCommittee)
	data = append(data, committeeData...)
	
	// 添加承诺
	data = append(data, commitments...)
	
	// 计算哈希
	hash := sha256.Sum256(data)
	return hash[:]
}

// generateThresholdSignature 生成阈值签名
func (c *CBRProtocol) generateThresholdSignature(digest []byte) ([]byte, error) {
	// 这里应该调用实际的阈值签名
	// 目前使用占位实现
	signature := []byte("threshold_signature_placeholder")
	return signature, nil
}

// installCheckpoint 安装检查点
func (c *CBRProtocol) installCheckpoint(checkpoint *Checkpoint) error {
	log.Printf("[CBR] Installing checkpoint for epoch %d", checkpoint.Epoch)
	
	// 验证检查点
	if err := c.verifyCheckpoint(checkpoint); err != nil {
		return err
	}
	
	// 安装新配置
	c.mu.Lock()
	c.checkpoint = checkpoint
	c.mu.Unlock()
	
	log.Printf("[CBR] Checkpoint installed successfully")
	return nil
}

// verifyCheckpoint 验证检查点
func (c *CBRProtocol) verifyCheckpoint(checkpoint *Checkpoint) error {
	// 验证签名
	if !c.verifyThresholdSignature(checkpoint.Digest, checkpoint.Signature) {
		return fmt.Errorf("invalid threshold signature")
	}
	
	// 验证摘要
	expectedDigest := c.generateDigest(checkpoint.Committee, checkpoint.Commitments)
	if string(expectedDigest) != string(checkpoint.Digest) {
		return fmt.Errorf("invalid digest")
	}
	
	return nil
}

// verifyThresholdSignature 验证阈值签名
func (c *CBRProtocol) verifyThresholdSignature(digest, signature []byte) bool {
	// 这里应该调用实际的阈值签名验证
	// 目前使用占位实现
	return true
}

// GetStatus 获取协议状态
func (c *CBRProtocol) GetStatus() map[string]interface{} {
	c.mu.RLock()
	defer c.mu.RUnlock()
	
	return map[string]interface{}{
		"state":        c.state,
		"epoch":        c.checkpoint.Epoch,
		"committee_n":  c.checkpoint.Committee.N,
		"committee_t":  c.checkpoint.Committee.T,
		"committee_l":  c.checkpoint.Committee.L,
		"threshold":    c.checkpoint.Committee.T + c.checkpoint.Committee.L + 1,
	}
}

// 修改原有的ADKR函数，集成CBR协议
func ADKR(
	sid string, pid, n, f int, g, h *crypto.G1, ePKs []crypto.G1, my_eSK crypto.ZR,
	msgInCh <-chan Message, msgOutCh chan<- Message,
) {
	log.Printf("ADKR-SID:%s PID:%d Starting CBR-enhanced protocol logic...", sid, pid)
	
	// 创建CBR配置
	config := &CBRConfig{
		T:       f, // 容错节点数
		L:       1, // 默认L=1
		N:       n, // 总节点数
		KzgPP:   []byte("kzg_public_params_placeholder"),
		Timeout: 30 * time.Second,
	}
	
	// 创建委员会
	oldCommittee := dycaps.Committee{
		Members: generateMemberList(n),
		T:       f,
		N:       n,
		L:       1,
	}
	
	newCommittee := dycaps.Committee{
		Members: generateMemberList(n), // 可以是不同的成员列表
		T:       f,
		N:       n,
		L:       1,
	}
	
	// 创建RBC、MVBA、阈值签名接口（占位实现）
	rbc := &PlaceholderRBC{}
	mvba := &PlaceholderMVBA{}
	threshold := &PlaceholderThresholdSig{}
	
	// 创建CBR协议实例
	cbr := NewCBRProtocol(config, rbc, mvba, threshold)
	
	// 执行重配置
	if err := cbr.ReconfigureWithCBR(oldCommittee, newCommittee); err != nil {
		log.Printf("CBR reconfiguration failed: %v", err)
		return
	}
	
	log.Printf("CBR reconfiguration completed successfully")
}

// 占位实现
type PlaceholderRBC struct{}
func (r *PlaceholderRBC) Broadcast(data []byte) error { return nil }
func (r *PlaceholderRBC) Receive() ([]byte, error) { return []byte{}, nil }

type PlaceholderMVBA struct{}
func (m *PlaceholderMVBA) Propose(proposal []byte) error { return nil }
func (m *PlaceholderMVBA) Decide() ([]byte, error) { return []byte{}, nil }

type PlaceholderThresholdSig struct{}
func (t *PlaceholderThresholdSig) Sign(data []byte) ([]byte, error) { return []byte{}, nil }
func (t *PlaceholderThresholdSig) Verify(data []byte, signature []byte) bool { return true }
func (t *PlaceholderThresholdSig) Combine(signatures [][]byte) ([]byte, error) { return []byte{}, nil }

// 辅助函数
func generateMemberList(n int) []string {
	members := make([]string, n)
	for i := 0; i < n; i++ {
		members[i] = strconv.Itoa(i)
	}
	return members
}
